package com.persondemo.videoappliction.ui.video;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.persondemo.videoappliction.R;
import com.persondemo.videoappliction.bean.MainBean;
import com.persondemo.videoappliction.bean.UpdataBean;
import com.persondemo.videoappliction.component.ApplicationComponent;
import com.persondemo.videoappliction.component.DaggerHttpComponent;
import com.persondemo.videoappliction.event.GridEvent;
import com.persondemo.videoappliction.event.MainEvent;
import com.persondemo.videoappliction.runtimepermissions.PermissionsManager;
import com.persondemo.videoappliction.runtimepermissions.PermissionsResultAction;
import com.persondemo.videoappliction.ui.adapter.MainGridViewAdapter;
import com.persondemo.videoappliction.ui.adapter.AnimeAdapter;
import com.persondemo.videoappliction.ui.adapter.MovieAdapter;
import com.persondemo.videoappliction.ui.adapter.TVAdapter;
import com.persondemo.videoappliction.ui.anime.AnimeActivity;
import com.persondemo.videoappliction.ui.base.BaseFragment;
import com.persondemo.videoappliction.ui.movie.MovieActivity;
import com.persondemo.videoappliction.ui.search.SearchActivity;
import com.persondemo.videoappliction.ui.tv.TvActivity;
import com.persondemo.videoappliction.ui.video.contract.MainContract;
import com.persondemo.videoappliction.ui.video.presenter.MainPresenter;
import com.persondemo.videoappliction.utils.ImageLoaderUtil;
import com.persondemo.videoappliction.utils.PreferenceUtil;
import com.persondemo.videoappliction.utils.RxDeviceTool;
import com.persondemo.videoappliction.utils.T;
import com.persondemo.videoappliction.utils.Updataurl;
import com.persondemo.videoappliction.widget.MyGridView;

import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import org.simple.eventbus.EventBus;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static android.Manifest.permission.WRITE_SETTINGS;

/**
 * Created by Administrator on 2018/3/20.
 */

public class MainFragment extends BaseFragment<MainPresenter> implements MainContract.View {
    @BindView(R.id.rl_search)
    RelativeLayout rlSearch;
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.recycler_tv)
    RecyclerView recyclerTv;
    private static final String TAG = "MainFragment";
    @BindView(R.id.include_type_01)
    LinearLayout includeType01;
    @BindView(R.id.include_type_02)
    LinearLayout includeType02;
    @BindView(R.id.include_type_03)
    LinearLayout includeType03;
    @BindView(R.id.include_type_04)
    LinearLayout includeType04;
    @BindView(R.id.rl_more_movie)
    RelativeLayout rlMoreMovie;
    @BindView(R.id.rl_more_tv)
    RelativeLayout rlMoreTv;
    @BindView(R.id.recycler_movie)
    RecyclerView recyclerMovie;
    @BindView(R.id.main_tv_img)
    ImageView mainTvImg;
    List<MainBean.DataBean.AdListBean> adListBeen;//广告业数据
    List<MainBean.DataBean.DlistBean> dlistBeen;//电影数据
    List<MainBean.DataBean.DmlistBean> dmlistBeen; //动漫数据
    List<MainBean.DataBean.DslistBean> dslistBeen;//电视剧数据
    List<MainBean.DataBean.TypeslistBean> typeslistBeen;//类型数据
    @BindView(R.id.main_grid)
    MyGridView mainGrid;
    MainGridViewAdapter mainGridViewAdapter;
    MovieAdapter movieAdapter;
    TVAdapter tvAdapter;
    AnimeAdapter animeAdapter;
    @BindView(R.id.rl_more_anime)
    RelativeLayout rlMoreAnime;
    @BindView(R.id.recycler_anime)
    RecyclerView recyclerAnime;
    View footview;
    private TextView foot_version;
    String imei = "";
    ProgressDialog m_progressDlg;
    Handler m_mainHandler;
    String m_appNameStr = "片趣.apk";
    public static int OVERLAY_PERMISSION_REQ_CODE = 1234;
    public static MainFragment newInstance() {
        Bundle args = new Bundle();
        MainFragment fragment = new MainFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getContentLayout() {
        return R.layout.module_fragment_video;
    }

    @Override
    public void initInjector(ApplicationComponent appComponent) {
        DaggerHttpComponent.builder()
                .applicationComponent(appComponent)
                .build()
                .inject(this);
    }

    @Override
    public void bindView(View view, Bundle savedInstanceState) {
        footview = LayoutInflater.from(getActivity()).inflate(R.layout.footview, null);
        foot_version = footview.findViewById(R.id.foot_version);
        foot_version.setText("当前版本：" + RxDeviceTool.getVerName(getActivity()));
        recyclerTv.setLayoutManager(new GridLayoutManager(getActivity(), 3));
        recyclerMovie.setLayoutManager(new GridLayoutManager(getActivity(), 3));
        recyclerAnime.setLayoutManager(new GridLayoutManager(getActivity(), 3));
        movieAdapter = new MovieAdapter(dlistBeen, getContext());
        tvAdapter = new TVAdapter(dslistBeen, getContext());
        animeAdapter = new AnimeAdapter(dmlistBeen, getContext());
        recyclerTv.setAdapter(tvAdapter);
        recyclerMovie.setAdapter(movieAdapter);
        recyclerAnime.setAdapter(animeAdapter);
        recyclerTv.setNestedScrollingEnabled(false);
        recyclerMovie.setNestedScrollingEnabled(false);
        recyclerAnime.setNestedScrollingEnabled(false);

        //设置banner样式
        banner.setBannerStyle(BannerConfig.NUM_INDICATOR_TITLE)
                .setImageLoader(new ImageLoader() {
                    @Override
                    public void displayImage(Context context, Object path, ImageView imageView) {
                        //Glide 加载图片简单用法
                        ImageLoaderUtil.LoadImage(getActivity(), path, imageView);
                    }
                })
                .setDelayTime(3000)
                .setIndicatorGravity(BannerConfig.RIGHT);
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                if (adListBeen != null && adListBeen.size() > 0) {
                    if (adListBeen.get(position).getUrl().contains("http")) {
                        Intent intent = new Intent(getActivity(), WeBviewActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putString("title", adListBeen.get(position).getUrl());
                        intent.putExtras(bundle);
                        startActivity(intent);
                    } else {
                        gotovideodetils(Integer.parseInt(adListBeen.get(position).getUrl()));
                    }
                }
            }
        });
        movieAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (dslistBeen != null && dslistBeen.size() > 0) {
                    gotovideodetils(dlistBeen.get(position).getId());
                }
            }
        });
        tvAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (dslistBeen != null && dslistBeen.size() > 0) {
                    gotovideodetils(dslistBeen.get(position).getId());
                }
            }
        });
        animeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (dmlistBeen != null && dmlistBeen.size() > 0) {
                    gotovideodetils(dmlistBeen.get(position).getId());
                }
            }
        });

    }

    @Override
    public void initData() {
        check();
        m_mainHandler = new Handler();
        m_progressDlg = new ProgressDialog(getActivity());
        m_progressDlg.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        m_progressDlg.setCanceledOnTouchOutside(false);
        // 设置ProgressDialog 的进度条是否不明确 false 就是不设置为不明确
        m_progressDlg.setIndeterminate(false);
        adListBeen = new ArrayList<>();
        typeslistBeen = new ArrayList<>();
        dmlistBeen = new ArrayList<>();
        dlistBeen = new ArrayList<>();
        dslistBeen = new ArrayList<>();
        if (mPresenter != null) {
            showLoadingDialog();
            mPresenter.getdetilsdatas(imei);
            mPresenter.getupdata();
        }
    }

    private void check() {
        PermissionsManager.getInstance().requestPermissionsIfNecessaryForResult(getActivity(), new String[]{
                Manifest.permission.READ_PHONE_STATE,Manifest.permission.WRITE_EXTERNAL_STORAGE,
                 Manifest.permission.WRITE_SETTINGS,
                 Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION
        }, new PermissionsResultAction() {
            @Override
            public void onGranted() {
                imei = RxDeviceTool.getIMEI(getActivity());
                if (!TextUtils.isEmpty(imei)) {
                    PreferenceUtil.put("imei", imei);
                }
            }
            @Override
            public void onDenied(String permission) {
                T.showShort(getActivity(), "用户拒绝授权");
            }
        });
    }

    @Override
    public void onRetry() {
    }

    @OnClick({R.id.include_type_01, R.id.include_type_02, R.id.include_type_03,
            R.id.include_type_04, R.id.rl_more_movie, R.id.rl_more_tv, R.id.rl_search, R.id.rl_more_anime})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_search:
                startActivity(new Intent(getActivity(), SearchActivity.class));
                getActivity().overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                break;
            case R.id.include_type_01:
                startActivity(new Intent(getActivity(), MovieActivity.class));
                getActivity().overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
                break;
            case R.id.include_type_02:
                startActivity(new Intent(getActivity(), AnimeActivity.class));
                getActivity().overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
                break;
            case R.id.include_type_03:
                startActivity(new Intent(getActivity(), TvActivity.class));
                getActivity().overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
                break;
            case R.id.include_type_04:
                goMovie("会员中心");
                break;
            case R.id.rl_more_movie:
                startActivity(new Intent(getActivity(), MovieActivity.class));
                getActivity().overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
                break;
            case R.id.rl_more_tv:
                startActivity(new Intent(getActivity(), TvActivity.class));
                getActivity().overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
                break;
            case R.id.rl_more_anime:
                startActivity(new Intent(getActivity(), AnimeActivity.class));
                getActivity().overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
                break;
        }
    }

    private void goMovie(String title) {
        EventBus.getDefault().post(new MainEvent(title));
    }

    private void startgo(MainBean.DataBean.TypeslistBean bean) {
        Intent intent = null;
        Bundle bundle = new Bundle();
        switch (bean.getType()) {
            case 1:
                intent = new Intent(getActivity(), MovieActivity.class);
                bundle.putString("title", bean.getTypes_name());
                intent.putExtras(bundle);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
                break;
            case 2:
                intent = new Intent(getActivity(), TvActivity.class);
                bundle.putString("title", bean.getTypes_name());
                intent.putExtras(bundle);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
                break;
            case 4:
                intent = new Intent(getActivity(), AnimeActivity.class);
                bundle.putString("title", bean.getTypes_name());
                intent.putExtras(bundle);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
                break;
        }
    }

    private void gridevent(MainBean.DataBean.TypeslistBean bean) {
        EventBus.getDefault().post(new GridEvent(bean));
    }

    private void gotovideodetils(int id) {
        Intent intent = new Intent(getActivity(), VideoDetilsActivity.class);
        Bundle bundle = new Bundle();
        bundle.putInt("id", id);
        intent.putExtras(bundle);
        startActivity(intent);
        getActivity().overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
    }

    @Override
    public void loaddata(MainBean mainBean) {
        if (mainBean.getStatus() == 1) {
            hideLoadingDialog();
            if (mainBean.getData().getAdList() != null && mainBean.getData().getAdList().size() > 0) {
                adListBeen.clear();
                adListBeen = mainBean.getData().getAdList();
                List<String> mTitleList = new ArrayList<>();
                List<String> mUrlList = new ArrayList<>();
                for (int i = 0; i < mainBean.getData().getAdList().size(); i++) {
                    mTitleList.add(mainBean.getData().getAdList().get(i).getName());
                    mUrlList.add(mainBean.getData().getAdList().get(i).getPic());
                }
                if (mUrlList.size() > 0) {
                    banner.setImages(mUrlList);
                    banner.setBannerTitles(mTitleList);
                    banner.start();
                }
            }
            if (mainBean.getData().getTypeslist() != null && mainBean.getData().getTypeslist().size() > 0) {
                typeslistBeen.clear();
                typeslistBeen = mainBean.getData().getTypeslist();
                //类型赋值
                mainGridViewAdapter = new MainGridViewAdapter(getContext(), typeslistBeen);
                mainGrid.setAdapter(mainGridViewAdapter);
                mainGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                        gridevent(typeslistBeen.get(position));
                        startgo(typeslistBeen.get(position));
                    }
                });
            }
            if (mainBean.getData().getDlist() != null && mainBean.getData().getDlist().size() > 0) {
                dlistBeen.clear();
                dlistBeen = mainBean.getData().getDlist();
                movieAdapter.setNewData(dlistBeen);
            }
            if (mainBean.getData().getDmlist() != null && mainBean.getData().getDmlist().size() > 0) {
                dmlistBeen.clear();
                animeAdapter.removeAllFooterView();
                dmlistBeen = mainBean.getData().getDmlist();
                animeAdapter.setNewData(dmlistBeen);
                animeAdapter.addFooterView(footview);
            }
            if (mainBean.getData().getDslist() != null && mainBean.getData().getDslist().size() > 0) {
                dslistBeen.clear();
                dslistBeen = mainBean.getData().getDslist();
                tvAdapter.setNewData(dslistBeen);
            }
            showSuccess();
        } else {
            T.showShort(getActivity(), mainBean.getMsg());
        }
    }

    @Override
    public void showFaild() {
        T.showShort(getContext(), "加载失败！");
        super.showFaild();
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    @Override
    public void loadupdata(UpdataBean updataBean) {
        if (updataBean == null || updataBean.getStatus() != 1) {
            showFaild();
        } else {
            if (getActivity().isDestroyed() == false) {
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//                   askForPermission();
//                }
                updata(updataBean.getData().getBanbenyrl(), updataBean.getData().getBanben());
            }
        }
    }

    /**
     * 请求用户给予悬浮窗的权限
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    public void askForPermission() {
        if (!Settings.canDrawOverlays(getActivity())) {
            Toast.makeText(getActivity(), "当前无权限，请授权！", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                    Uri.parse("package:" + getActivity().getPackageName()));
            startActivityForResult(intent, OVERLAY_PERMISSION_REQ_CODE);
        }
    }

    /**
     * 用户返回
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == OVERLAY_PERMISSION_REQ_CODE) {
            if (!Settings.canDrawOverlays(getActivity())) {
                Toast.makeText(getActivity(), "权限授予失败，无法开启悬浮窗", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getActivity(), "权限授予成功！", Toast.LENGTH_SHORT).show();

            }

        }
    }

    private void updata(String url, String banben) {
        String nowversion = RxDeviceTool.getAppVersionName(getActivity()).replaceAll("\\.", "");
        String fuwu = banben.replaceAll("\\.", "");
        if (TextUtils.isEmpty(nowversion) && TextUtils.isEmpty(fuwu)) {
            return;
        }
        Log.e("gengxin", "当前版本：" + Integer.parseInt(nowversion) + "服务器版本：" + Integer.parseInt(fuwu));
        if (Integer.parseInt(nowversion) < Integer.parseInt(fuwu)) {
            String str = "当前版本：" + RxDeviceTool.getAppVersionName(getActivity()) + "" +
                    " ,发现新版本：" + banben + " ,是否更新？";
            Updataurl.setUrl(url);
            Dialog dialog = new AlertDialog.Builder(getContext())
                    .setTitle("软件更新")
                    .setMessage(str)
                    // 设置内容
                    .setPositiveButton("更新",// 设置确定按钮
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    m_progressDlg.setTitle("正在下载");
                                    m_progressDlg.setMessage("请稍候...");
                                    downFile(url);
//                                    if (Environment.getExternalStorageState().equals(
//                                            Environment.MEDIA_MOUNTED)) {
//                                        Intent intent = new Intent(getActivity(), UpdataService.class);
//                                        getActivity().startService(intent);
//                                        T.showShort(getActivity(), "正在后台更新最新版本");
//                                    } else {
//                                        Toast.makeText(getActivity(), "SD卡不可用，请插入SD卡",
//                                                Toast.LENGTH_SHORT).show();
//                                    }
                                }
                            })
                    .setNegativeButton("暂不更新",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                                    int whichButton) {
                                    //关闭对话框
                                    dialog.dismiss();
                                }
                            }).create();// 创建
            // 显示对话框
            dialog.show();
        }
    }

    /**
     * 下载安装包
     *
     * @param url
     */
    private void downFile(final String url) {
        m_progressDlg.show();
        new Thread() {
            public void run() {
                try {
                    URL url1 = new URL(url);
                    HttpURLConnection connection = (HttpURLConnection) url1.openConnection();
                    long length = connection.getContentLength();
                    m_progressDlg.setMax((int) length);// 设置进度条的最大值
                    InputStream is = (InputStream) connection.getContent();
                    FileOutputStream fileOutputStream = null;
                    if (is != null) {
                        File file = new File(
                                Environment.getExternalStorageDirectory()
                                , m_appNameStr);
                        fileOutputStream = new FileOutputStream(file);
                        byte[] buf = new byte[4154];
                        int ch = -1;
                        int count = 0;
                        while ((ch = is.read(buf)) != -1) {
                            fileOutputStream.write(buf, 0, ch);
                            count += ch;
                            if (length > 0) {
                                m_progressDlg.setProgress(count);
                            }
                        }
                    }
                    fileOutputStream.flush();
                    if (fileOutputStream != null) {
                        fileOutputStream.close();
                    }
                    down(); // 告诉HANDER已经下载完成了，可以安装了
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    /**
     * 告诉HANDER已经下载完成了，可以安装了
     */
    private void down() {
        m_mainHandler.post(new Runnable() {
            public void run() {
                m_progressDlg.cancel();
                update();
            }
        });
    }

    /**
     * 安装程序
     */
    void update() {
        File file = new File(Environment.getExternalStorageDirectory()
                , m_appNameStr);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

            Uri fileUri = FileProvider.getUriForFile(getActivity(), getActivity().getApplicationContext().getPackageName() + ".fileProvider", file);
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(fileUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        startActivity(intent);


    }


}
